package com.cc.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.common.utils.PageUtils;
import com.cc.common.utils.R;
import com.cc.common.utils.ResponseData;
import com.cc.common.utils.ResultMsg;
import com.cc.user.entity.CertificatePictureEntity;
import com.cc.user.entity.EmployeeCustomerEntity;
import com.cc.user.entity.UserEntity;
import com.cc.user.service.CertificatePictureService;
import com.cc.user.service.EmployeeCustomerService;
import com.cc.user.service.UserService;
import com.cc.user.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 
 *
 * @author leifengyang
 * @email leifengyang@gmail.com
 * @date 2020-12-11 11:30:58
 */
@RestController
@RequestMapping("user/employeecustomer")
@Api(tags="业务员客户")
public class EmployeeCustomerController {
    @Autowired
    private EmployeeCustomerService employeeCustomerService;

    @Autowired
    private CertificatePictureService certificatePictureService;

    @Autowired
    private UserService userService;

    @PostMapping("/getCustomerDetailByEidCid")
    @ApiOperation("后台查看客户详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "eid",value = "业务员id",paramType = "query",dataType = "Long",required = true),
        @ApiImplicitParam(name = "cid",value = "客户id",paramType = "query",dataType = "Long",required = true)
    })
    public ResponseData<List<OfflineOrderNewVo>> getCustomerDetailByEidCid(@RequestParam("eid") Long eid,@RequestParam("cid") Long cid) {
        List<OfflineOrderNewVo> offlineOrderNewVos = employeeCustomerService.getCustomerDetailByEidCid(eid,cid);
        if (offlineOrderNewVos == null)  return ResponseData.success("该客户无订单",true);
        //给每个订单添加每个订单下的所有商品
        for(OfflineOrderNewVo offlineOrderNewVo:offlineOrderNewVos) {
            //查询该订单下的所有商品
            List<OfflineOrderProductNewVo> offlineOrderProducts = employeeCustomerService.getOfflineOrderProductsById(offlineOrderNewVo.getId());
            offlineOrderNewVo.setOfflineOrderProducts(offlineOrderProducts);
        }
        return ResponseData.success(offlineOrderNewVos);
    }

    @PostMapping("/changeEmpCusLinkSatus")
    @ApiOperation("后台根据业务员客户id解除关系")
    @ApiImplicitParam(name = "id", value = "业务员客户id", paramType = "query", dataType = "Long", required = true)
    public ResponseData changeEmpCusLinkSatus(@RequestParam("id") Long id) {
        EmployeeCustomerEntity employeeCustomerEntity = employeeCustomerService.getById(id);
        if (employeeCustomerEntity == null) return ResponseData.success("查询失败，没有该关系");
        certificatePictureService.deleteCustomerPictures(employeeCustomerEntity.getCid());
        boolean flag = employeeCustomerService.removeById(id);
        if (flag)   return ResponseData.success("解除成功");
        return ResponseData.success("解除失败");
    }

    @PostMapping("/getEmployeesCustomers")
    @ApiOperation("后台通过业务员、客户手机号查看业务员客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "empMobile", value = "业务员手机号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "cusMobile", value = "客户手机号", paramType = "query", dataType = "String"),
    })
    public ResponseData<PageUtils> getEmployeesCustomers(@RequestParam(required = true) Map<String, Object> params, @RequestParam("empMobile") String empMobile, @RequestParam("cusMobile") String cusMobile) {
        List<EmployeeCustomerVo> employeesCustomers = employeeCustomerService.getEmployeesCustomers(empMobile,cusMobile);
        //分页
        int page = Integer.parseInt((String) params.get("page"));
        int limit = Integer.parseInt((String) params.get("limit"));

        int totalCount = employeesCustomers.size();
        List<EmployeeCustomerVo> list = new ArrayList<>();
        for(int i = (page-1)*limit;i<page*limit;i++){
            if(i<=employeesCustomers.size()-1) {
                list.add(employeesCustomers.get(i));
            }
        }
        PageUtils pageUtils = new PageUtils(list, totalCount, limit, page);
        return ResponseData.success(pageUtils);
    }

    @PostMapping("/getCustomersByPhoneOrName")
    @ApiOperation("通过手机号或姓名查看客户列表")
    @ApiImplicitParam(name = "condition",value = "查询条件，姓名或手机号",paramType = "query",dataType = "String",required = true)
    public ResponseData<List<CustomerVo>> getCustomersByPhoneOrName(@RequestParam("condition") String condition,HttpSession session) {
        UserEntity employee = (UserEntity) session.getAttribute("loginuser");
        Long eid = employee.getUid();

        List<CustomerVo> customers = employeeCustomerService.getCustomersByPhoneOrName(eid,condition);

        return ResponseData.success(customers);
    }

    @PostMapping("/getAllCustomers")
    @ApiOperation("查看客户列表")
    public ResponseData<List<CustomerVo>> getAllCustomers(HttpSession session) {
        UserEntity employee = (UserEntity) session.getAttribute("loginuser");
        Long eid = employee.getUid();

        List<CustomerVo> customers = employeeCustomerService.getAllCustomers(eid);

        return ResponseData.success(customers);
    }

    @PostMapping("/getCustomerDetailByCid")
    @ApiOperation("查看客户详情")
    @ApiImplicitParam(name = "cid",value = "客户id",paramType = "query",dataType = "Long",required = true)
    public ResponseData<CustomerDetailVo> getCustomerDetail(@RequestParam("cid") Long cid,HttpSession session) {
        UserEntity employee = (UserEntity) session.getAttribute("loginuser");
        Long eid = employee.getUid();

        CustomerDetailVo customerDetailVo = employeeCustomerService.getCustomerDetailByCid(cid);

        List<CertificatePictureEntity> certificatePictureEntities = certificatePictureService.getPicturesByCid(cid);
        List<String> mentouPictures = new ArrayList<>();
        List<String> chengliePictures = new ArrayList<>();
        List<String> hetongPictures = new ArrayList<>();
        for (CertificatePictureEntity one:certificatePictureEntities){
            Integer type = one.getPictureType();
            String picture = one.getPicture();
            if (type == 0)  mentouPictures.add(picture);
            else if (type == 1) chengliePictures.add(picture);
            else if (type == 2) hetongPictures.add(picture);
        }
        customerDetailVo.setMentouPictures(mentouPictures);
        customerDetailVo.setChengliePictures(chengliePictures);
        customerDetailVo.setHetongPictures(hetongPictures);

        //记录业务员总回款和应收款
        BigDecimal collection = new BigDecimal("0");
        BigDecimal receivables = new BigDecimal("0");
        List<OfflineOrderNewVo> offlineOrderNewVos = employeeCustomerService.getCustomerDetailByEidCid(eid,cid);
        if (offlineOrderNewVos != null) {
            for (OfflineOrderNewVo offlineOrderNewVo : offlineOrderNewVos) {
                //查询该订单下的所有商品
                List<OfflineOrderProductNewVo> offlineOrderProducts = employeeCustomerService.getOfflineOrderProductsById(offlineOrderNewVo.getId());
                offlineOrderNewVo.setOfflineOrderProducts(offlineOrderProducts);
                //累加回款和应收款
                collection = collection.add(offlineOrderNewVo.getAmountsPaid());
                receivables = receivables.add(offlineOrderNewVo.getAmountsPayable().subtract(offlineOrderNewVo.getAmountsPaid()));
            }
            customerDetailVo.setOfflineOrders(offlineOrderNewVos);
        }
        customerDetailVo.setCollection(collection);
        customerDetailVo.setReceivables(receivables);

        return ResponseData.success(customerDetailVo);
    }

    @PostMapping("/addCustomer")
    @ApiOperation("添加客户")
    public ResponseData addCustomer(@RequestBody AddCustomerDetailVo customerDetail,HttpSession session) {

        UserEntity employee = (UserEntity) session.getAttribute("loginuser");
        Long eid = employee.getUid();
        // 根据电话号码获取客户id
        Long cid = userService.getCidByPhone(customerDetail.getMobile());
        if (cid == null){
            return ResponseData.success("未查询到该客户，添加失败",false);
        }
        // 添加员工与客户的对应关系记录
        EmployeeCustomerEntity temp = employeeCustomerService.getOne(new QueryWrapper<EmployeeCustomerEntity>().eq("cid", cid));
        if (temp != null){
            return ResponseData.success("该客户已有业务员，请勿重复添加",false);
        }
        EmployeeCustomerEntity employeeCustomerEntity = new EmployeeCustomerEntity();
        employeeCustomerEntity.setCid(cid);
        employeeCustomerEntity.setEid(eid);
        employeeCustomerService.save(employeeCustomerEntity);

        // 添加照片
        List<CertificatePictureEntity> list = new ArrayList<>();
        for (String picture:customerDetail.getMentouPictures()) {
            CertificatePictureEntity pictureEntity = new CertificatePictureEntity();
            pictureEntity.setCid(cid);
            pictureEntity.setPicture(picture);
            pictureEntity.setPictureType(0);
            list.add(pictureEntity);
        }
        for (String picture:customerDetail.getChengliePictures()) {
            CertificatePictureEntity pictureEntity = new CertificatePictureEntity();
            pictureEntity.setCid(cid);
            pictureEntity.setPicture(picture);
            pictureEntity.setPictureType(1);
            list.add(pictureEntity);
        }
        for (String picture:customerDetail.getHetongPictures()) {
            CertificatePictureEntity pictureEntity = new CertificatePictureEntity();
            pictureEntity.setCid(cid);
            pictureEntity.setPicture(picture);
            pictureEntity.setPictureType(2);
            list.add(pictureEntity);
        }
        certificatePictureService.saveBatch(list);

        return ResponseData.success("添加成功",true);
    }

//    @PostMapping("/getCustomerName")
//    @ApiOperation("根据手机号码获取客户昵称")
//    @ApiImplicitParam(name = "phone",value = "客户手机号码",paramType = "query",dataType = "String",required = true)
//    public ResponseData<CustomerNameVo> getCustomerName(@RequestParam("phone") String phone) {
//        String cname = userService.getCnameByPhone(phone);
//        if (cname == null)
//            return ResponseData.success("该用户未注册",true);
//        CustomerNameVo customerNameVo = new CustomerNameVo();
//        customerNameVo.setNickname(cname);
//        return ResponseData.success(customerNameVo);
//    }
    /**
     * 列表
     */


//    /**
//     * 信息
//     */
//    @GetMapping("/info/{id}")
//    public R info(@PathVariable("id") Long id){
//		EmployeeCustomerEntity employeeCustomer = employeeCustomerService.getById(id);
//
//        return R.ok().put("employeeCustomer", employeeCustomer);
//    }
//
//    /**
//     * 保存
//     */
//    @PostMapping("/save")
//    public R save(@RequestBody EmployeeCustomerEntity employeeCustomer){
//		employeeCustomerService.save(employeeCustomer);
//
//        return R.ok();
//    }
//
//    /**
//     * 修改
//     */
//    @PostMapping("/update")
//    public R update(@RequestBody EmployeeCustomerEntity employeeCustomer){
//		employeeCustomerService.updateById(employeeCustomer);
//
//        return R.ok();
//    }
//
//    /**
//     * 删除
//     */
//    @PostMapping("/delete")
//    public R delete(@RequestBody Long[] ids){
//		employeeCustomerService.removeByIds(Arrays.asList(ids));
//
//        return R.ok();
//    }
//
    @GetMapping("/getEidByCid/{cid}")
    public Long getEidByCid(@PathVariable("cid") Long cid){
        EmployeeCustomerEntity one = employeeCustomerService.getOne(new QueryWrapper<EmployeeCustomerEntity>().eq("cid", cid));
        return one.getEid();
    }
}
